﻿using BAL;
using DAL.DataTransferObject;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Module.QLHangHoa;
using System.Data.SqlClient;
using DAL;

namespace Module.QLHangHoa
{
    public partial class frmQLHangHoa : Form
    {
        public HangHoaBAO hhBAO = new HangHoaBAO();
        public frmQLHangHoa()
        {
            InitializeComponent();
        }

        Timer timer = new Timer();
        private void frmQLHangHoa_Load(object sender, EventArgs e)
        {
            loadData();
            DGV1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            bt_update.Enabled = false;
            btDelete.Enabled = false;
            timer.Interval = 10;
            timer.Start();
            timer.Tick += timer_Tick;
        }

        void timer_Tick(object sender, EventArgs e)
        {
            btReset.PerformClick();
            timer.Stop();
        }

        public void loadData()
        {
            List<HangHoa> listHH = hhBAO.HangHoa_GetData();
            Console.WriteLine(listHH.Count);
            DGV1.DataSource = listHH;
            DGV1.Rows[0].Selected = false;
            autoComplte(cboLH, "LoaiHang");
            autoComplte(cboNPP, "MaNPP");
            autoComplte(cboKC, "KhoChua");
        }

        public bool CheckComboBoxItem(ComboBox cbox)
        {
            //if (tb.AutoCompleteCustomSource.Contains(tb.Text))
            //    return true;
            if (cbox.Items.Contains(cbox.Text))
                return true;
            return false;
        }

        private void bt_addNew_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtMH.Text.Length == 0) throw new Exception("Mã hàng không được bỏ trống");
                if (txtTenHang.Text.Length == 0) throw new Exception("Tên hàng không được bỏ trống");
                if (cboNPP.Text.Length == 0) throw new Exception("Mã nhà phân phối không được bỏ trống");
                if (Convert.ToInt32(txtSL.Text) == 0 || txtSL.Text.Length == 0) throw new Exception("Số lượng hàng phải lớn hơn 0");
                if (Convert.ToInt32(txtGG.Text) == 0 || txtGG.Text.Length == 0) throw new Exception("Giá gốc phải lớn hơn 0 ");
                if (Convert.ToInt32(txtSLDG.Text) == 0 || txtSLDG.Text.Length == 0) throw new Exception("Số lượng đóng gói lớn hơn 1");
                if (txtTNSX.Text.Length == 0) throw new Exception("Tên nhà sản xuất hàng không được bỏ trống"); txtTNSX.Focus();
                if (txtXX.Text.Length == 0) throw new Exception("Xuất xứ không được bỏ trống"); txtXX.Focus();
                if (cboKC.Text.Length == 0) throw new Exception("Kho chứa hàng không được bỏ trống"); cboKC.Focus();
                if (dtNSX.Value > dtHSD.Value) throw new Exception("Ngày sản xuất phải trước hạn sử dụng"); dtNSX.Focus();
                if (hhBAO.HangHoa_CheckId(txtMH.Text))
                    throw new Exception("Trùng mã hàng !");
                if (!CheckComboBoxItem(cboLH) || !CheckComboBoxItem(cboKC) || !CheckComboBoxItem(cboNPP))
                    throw new Exception("Bạn phải chọn các giá trị có sẵn trong danh sách !");
                HangHoa hh = new HangHoa();
                getInfo(hh);
                hhBAO.HangHoa_AddNew(hh);
                reset();
                btReset.PerformClick();
            }
            catch (FormatException)
            {
                MessageBox.Show("Yêu cầu nhập số");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "ERROR");
            }
        }
        public void getInfo(HangHoa hh)
        {
            hh.maHang = txtMH.Text;
            hh.tenHang = txtTenHang.Text;
            hh.donVi = txtDV.Text;
            hh.maNPP = cboNPP.Text;
            hh.soLuong = Convert.ToInt32(txtSL.Text);
            //MessageBox.Show(txtSL.Text);
            hh.giaGoc = Convert.ToInt32(txtGG.Text);
            hh.giaDongGoi = Convert.ToInt32(txtGDG.Text);
            hh.soLuongDongGoi = Convert.ToInt32(txtSLDG.Text);
            hh.VAT = Convert.ToInt32(txtVAT.Text);
            hh.tenNSX = txtTNSX.Text;
            hh.ngaySX = dtNSX.Value;
            hh.hanSD = dtHSD.Value;
            hh.ghiChu = txtGhiChu.Text;
            hh.xuatXu = txtXX.Text;
            hh.khoChua = cboKC.Text;
            hh.loaiHang = cboLH.Text;

        }



        private void DGV_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (SearchClicked)
            {
                int rowIndex = 0;
                DataView dvTemp = new DataView();
                dvTemp = hhBAO.SelectAllViewHangHoa();
                rowIndex = AutoGenCode.GetRealIndexOfRow(DGV1.SelectedRows[0].Cells[1].Value.ToString(), dvTemp, 0);
                btsearch.PerformClick();
                DGV1.CurrentRow.Selected = false;
                //DGV1.Rows[rowIndex].Selected = true;
                DGV1.CurrentCell = DGV1[0, rowIndex];
                //DGV1.SelectedRows[rowIndex].Selected=true;
            }
            this.DataGridViewToInfor();
            bt_addNew.Enabled = false;
            txtMH.ReadOnly = true;
            bt_update.Enabled = true;
            btDelete.Enabled = true;
            //btsearch.Enabled = false;
            //txtTenHang.Enabled = false;
            //txtDV.Enabled = false;
            //txtMaNPP.Enabled = false;
            //txtTNSX.Enabled = false;
            //dtHSD.Enabled = false;
            //dtNSX.Enabled = false;
            //txtXX.Enabled = false;
            //txtLH.Enabled = false;
            //txtSLDG.Enabled = false;

        }

        public void DataGridViewToInfor()
        {
            txtMH.Text = Convert.ToString(DGV1.CurrentRow.Cells[1].Value);
            txtTenHang.Text = Convert.ToString(DGV1.CurrentRow.Cells[2].Value);
            txtDV.Text = Convert.ToString(DGV1.CurrentRow.Cells[3].Value); ;
            cboNPP.Text = Convert.ToString(DGV1.CurrentRow.Cells[4].Value);
            txtSL.Text = Convert.ToString(DGV1.CurrentRow.Cells[5].Value); ;
            txtGG.Text = Convert.ToString(DGV1.CurrentRow.Cells[6].Value);
            txtSLDG.Text = Convert.ToString(DGV1.CurrentRow.Cells[7].Value);
            txtGDG.Text = Convert.ToString(DGV1.CurrentRow.Cells[8].Value);
            txtVAT.Text = Convert.ToString(DGV1.CurrentRow.Cells[9].Value);
            txtTNSX.Text = Convert.ToString(DGV1.CurrentRow.Cells[10].Value);
            dtNSX.Value = Convert.ToDateTime(DGV1.CurrentRow.Cells[11].Value);
            dtHSD.Value = Convert.ToDateTime(DGV1.CurrentRow.Cells[12].Value);
            txtGhiChu.Text = Convert.ToString(DGV1.CurrentRow.Cells[13].Value);
            txtXX.Text = Convert.ToString(DGV1.CurrentRow.Cells[14].Value);
            cboLH.Text = Convert.ToString(DGV1.CurrentRow.Cells[15].Value);
            cboKC.Text = Convert.ToString(DGV1.CurrentRow.Cells[16].Value);
        }

        private void bt_update_Click(object sender, EventArgs e)
        {
            HangHoa hh = new HangHoa();
            getInfo(hh);
            hhBAO.HangHoa_Update(hh);
            loadData();
            reset();
        }

        private void btDelete_Click(object sender, EventArgs e)
        {
            HangHoa hh = new HangHoa();
            getInfo(hh);
            hh.soLuong = 0;
            hhBAO.HangHoa_Update(hh);
            loadData();
            reset();
        }

        public void reset()
        {

            txtMH.Text = AutoGenCode.GenNewCode("HangHoa");
            txtMH.ReadOnly = true;
            txtTenHang.Clear();
            txtDV.Clear();
            txtSL.Clear();
            txtGG.Clear();
            txtSLDG.Clear();
            txtGDG.Clear();
            txtVAT.Clear();
            txtTNSX.Clear();
            dtNSX.Value = DateTime.Now;
            dtHSD.Value = DateTime.Now;
            txtGhiChu.Clear();
            txtXX.Clear();
            cboNPP.Text = "";
            cboLH.Text = "";
            cboKC.Text = "";


            bt_update.Enabled = false;
            btDelete.Enabled = false;
            bt_addNew.Enabled = true;
            //btsearch.Enabled = true;
            txtMH.Enabled = true;
            txtTenHang.Enabled = true;
            txtDV.Enabled = true;
            txtTNSX.Enabled = true;
            dtHSD.Enabled = true;
            dtNSX.Enabled = true;
            txtXX.Enabled = true;
            cboLH.Enabled = true;
            txtSLDG.Enabled = true;
            btExp.Enabled = true;

        }

        private void btReset_Click(object sender, EventArgs e)
        {
            reset();
            loadData();
            for (int i = 0; i < DGV1.Rows.Count; i++)
            {
                DGV1.Rows[i].Cells[0].Value = (i + 1);
            }
        }



        bool SearchClicked = false;
        private string ToStringFilter(List<string> list)
        {
            Console.WriteLine(list.Count.ToString());
            string s = "";
            if (list.Count >= 2)
                for (int i = 0; i < list.Count - 1; i++)
                    s += list.ToArray()[i] + " AND ";
            s += list.ToArray()[list.Count - 1];
            return s;
        }


        DataView dv = new DataView();
        //string filterString = "";
        List<string> listStringFilter = new List<string>();
        private void btsearch_Click(object sender, EventArgs e)
        {
            if (!SearchClicked)
            {
                //MessageBox.Show("BAT");
                dv = hhBAO.SelectAllViewHangHoa();
                SearchClicked = true;
                btsearch.BackgroundImage = (Image)(Properties.Resources.ResourceManager.GetObject("TatTK"));
                reset();
                dtHSD.Enabled = dtNSX.Enabled = true;
                btReset.Enabled = btExp.Enabled = bt_addNew.Enabled = false;
                dtNSX.Value = dtNSX.MinDate;
                dtNSXKT.Value = dtNSXKT.MaxDate;
                dtHSD.Value = dtHSD.MinDate;
                dtHSDKT.Value = dtHSDKT.MaxDate;
                cboKC.Items.Add("Tat ca");
                cboLH.Items.Add("Tat ca");
                cboNPP.Items.Add("Tat ca");
                txtMH.Text = "";
                txtMH.ReadOnly = false;
                lblHSDDen.Visible = lblNSXDen.Visible = dtHSDKT.Visible = dtNSXKT.Visible = true;
                //return;
            }
            else
            {
                //MessageBox.Show("TAT");
                SearchClicked = false;
                btsearch.BackgroundImage = (Image)(Properties.Resources.ResourceManager.GetObject("BatTK"));
                reset();
                loadData();
                cboKC.Items.Remove("Tat ca");
                cboLH.Items.Remove("Tat ca");
                cboNPP.Items.Remove("Tat ca");
                btReset.Enabled = true;
                lblHSDDen.Visible = lblNSXDen.Visible = dtHSDKT.Visible = dtNSXKT.Visible = false;
                //return;
            }
        }


        private void FilterChanged(object sender, EventArgs e)
        {
            if (SearchClicked)
            {
                listStringFilter = new List<string>();

                listStringFilter.Add(String.Format("DonVi like '{0}%'", txtDV.Text));
                listStringFilter.Add(String.Format("Convert(GiaDongGoi,System.String) like '{0}%'", txtGDG.Text));
                listStringFilter.Add(String.Format("Convert(GiaGoc,System.String) like '{0}%'", txtGG.Text));
                listStringFilter.Add(String.Format("GhiChu like '{0}%'", txtGhiChu.Text));
                listStringFilter.Add(String.Format("MaHang like '{0}%'", txtMH.Text));
                listStringFilter.Add(String.Format("Convert(SoLuong,System.String) like '{0}%'", txtSL.Text));
                listStringFilter.Add(String.Format("Convert(SoLuongDongGoi,System.String) like '{0}%'", txtSLDG.Text));
                listStringFilter.Add(String.Format("TenHang like '{0}%'", txtTenHang.Text));
                listStringFilter.Add(String.Format("TenNSX like '{0}%'", txtTNSX.Text));
                listStringFilter.Add(String.Format("Convert(VAT,System.String) like '{0}%'", txtVAT.Text));
                listStringFilter.Add(String.Format("XuatXu like '{0}%'", txtXX.Text));

                if (cboKC.Text != "Tat ca")
                    listStringFilter.Add(String.Format("KhoChua like '{0}%'", cboKC.Text));
                else
                    listStringFilter.Add(String.Format("KhoChua like '%'", cboKC.Text));
                if (cboLH.Text != "Tat ca")
                    listStringFilter.Add(String.Format("Loaihang like '{0}%'", cboLH.Text));
                else
                    listStringFilter.Add(String.Format("Loaihang like '%'", cboLH.Text));
                if (cboNPP.Text != "Tat ca")
                    listStringFilter.Add(String.Format("MaNPP like '{0}%'", cboNPP.Text));
                else
                    listStringFilter.Add(String.Format("MaNPP like '%'", cboNPP.Text));

                listStringFilter.Add(String.Format("NgaySX >= '{0}' and NgaySX <= '{1}'", dtNSX.Value, dtNSXKT.Value));
                listStringFilter.Add(String.Format("HanSD >= '{0}' and HanSD <= '{1}'", dtHSD.Value, dtHSDKT.Value));


                dv.RowFilter = ToStringFilter(listStringFilter);
                DGV1.DataSource = dv;
            }
        }


        private void btExp_Click(object sender, EventArgs e)
        {
            List<HangHoa> listHH = hhBAO.HangHoa_CheckExp();
            if (listHH.Count == 0)
            {
                MessageBox.Show("Không có mặt hàng nào hết hạn", "ERROR");
                reset();
            }
            else
            {
                DGV1.DataSource = listHH;
                for (int i = 0; i < DGV1.Rows.Count; i++)
                {
                    DGV1.Rows[i].Cells[0].Value = (i + 1);

                }
            }
        }

        private void DGV1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
        public void autoComplte(ComboBox a, string sa)
        {
            //SqlDataReader dr = hhBAO.autoComplete();
            //AutoCompleteStringCollection auto = new AutoCompleteStringCollection();
            //while(dr.Read())
            //{
            //    auto.Add(dr[sa].ToString());
            //}
            //a.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            //a.AutoCompleteSource = AutoCompleteSource.CustomSource;
            //a.AutoCompleteCustomSource = auto;
            SqlDataReader dr = hhBAO.autoComplete();
            //AutoCompleteStringCollection auto = new AutoCompleteStringCollection();
            while (dr.Read())
            {
                if (!a.Items.Contains(dr[sa].ToString()))
                    a.Items.Add(dr[sa].ToString());
            }
            //a.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            //a.AutoCompleteSource = AutoCompleteSource.CustomSource;
            //a.AutoCompleteCustomSource = auto
        }


    }
}
